/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cc.altius.web.controller;

import cc.altius.model.*;
import cc.altius.service.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;

/**
 *
 * @author sagar
 */
@Controller
public class SmsController {

    //private static int RELATION_SELF = 6;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private CenterService centerService;
    @Autowired
    private OfficeLocationService officeLocationService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private LocumService locumService;
    @Autowired
    private AmbulanceService ambulanceService;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private SpecialistService specialistService;

    @ModelAttribute("centerList")
    public List<HealthSpringCenter> populateCenterList() {
        return centerService.getCenterList();
    }

//    @ModelAttribute("smsTypeList")
//    public List<SmsType> populateSmsTypeList() {
//        return smsService.getSmsTypeList();
//    }
    @ModelAttribute("smsSituationList")
    public List<SmsSituation> populateSmsSituationList() {
        return smsService.getSmsSituationList();
    }

    @ModelAttribute("doctorList")
    public List<Doctor> populateDoctorList() {
        return doctorService.getDoctorList();
    }

    @RequestMapping(value = "getCenterInfo.htm", method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxGetForCenterInfo(@RequestParam("centerId1") int centerId1) {
        System.out.println("inside doAjaxGetForCenterInfo");
        //ZipCodeArea zipCodeAreas = this.hospitalService.getZipCodeByZipCode(zipCode1);
        HealthSpringCenter healthSpringCenter = this.centerService.getCenterById(centerId1);
        Gson gson = new Gson();
        String json = gson.toJson(healthSpringCenter);
        System.out.println("json : " + json);
        return json.toString();
    }

    @RequestMapping(value = "getHospitalInfo.htm", method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxGetForHospitalInfo(@RequestParam("hospitalId1") int hospitalId1) {
        System.out.println("inside doAjaxGetForHospitalInfo");
        //ZipCodeArea zipCodeAreas = this.hospitalService.getZipCodeByZipCode(zipCode1);
        Hospital hospital = this.hospitalService.getHospitalById(hospitalId1);
        Gson gson = new Gson();
        String json = gson.toJson(hospital);
        System.out.println("json : " + json);
        return json.toString();
    }

    @RequestMapping(value = "getLocumInfo.htm", method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxGetForLocumInfo(@RequestParam("locumId1") int locumId1) {
        System.out.println("inside doAjaxGetForLocumInfo");
        //ZipCodeArea zipCodeAreas = this.hospitalService.getZipCodeByZipCode(zipCode1);
        Locum locum = this.locumService.getLocumById(locumId1);
        Gson gson = new Gson();
        String json = gson.toJson(locum);
        System.out.println("json : " + json);
        return json.toString();
    }

    //AutoComplete for Hospital
    @RequestMapping(value = "ajaxCallForSMSHospitalList.htm", method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxCallForHospitalList(HttpServletRequest request) {//ajaxCallForHospitalList
        System.out.println("inside ajaxCallForSMSHospitalList");
        String str = request.getParameter("term");
        String json;
        List<Hospital> hospitalListForSms = this.hospitalService.smsHospitalListForAutoComplete(str);
        System.out.println("list" + hospitalListForSms.size());
        Gson gson = new Gson();
        List list = new ArrayList();
        for (Hospital h : hospitalListForSms) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", h.getHospitalId());
            map.put("label", h.getHospitalName() + " ~ " + h.getContactSms() + " ~ " + h.getContactName() + " ~ " + h.getHospitalId());
            map.put("value", h.getHospitalName() + " ~ " + h.getContactSms() + " ~ " + h.getContactName() + " ~ " + h.getHospitalId());
            list.add(map);
        }
        Type typeList = new TypeToken<List>() {
        }.getType();
        json = gson.toJson(list, typeList);
        System.out.println("json :" + json);
        return json;
    }

    //AutoComplete for Hospital
    @RequestMapping(value = "ajaxCallForSMSType14HospitalList.htm", method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxCallForHospitalListForSmsTYpe14(HttpServletRequest request) {//ajaxCallForHospitalList
        System.out.println("inside ajaxCallForSMSHospitalList");
        String str = request.getParameter("term");
        String json;
        List<Hospital> hospitalListForSmsType14 = this.hospitalService.smsHospitalListForAutoComplete(str);
        System.out.println("list" + hospitalListForSmsType14.size());
        Gson gson = new Gson();
        List list = new ArrayList();
        for (Hospital h : hospitalListForSmsType14) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", h.getHospitalId());
            map.put("label", h.getHospitalName() + " ~ " + h.getContact1() + " ~ " + h.getHospitalId());
            map.put("value", h.getHospitalName() + " ~ " + h.getContact1() + " ~ " + h.getHospitalId());
            list.add(map);
        }
        Type typeList = new TypeToken<List>() {
        }.getType();
        json = gson.toJson(list, typeList);
        System.out.println("json :" + json);
        return json;
    }

    //Autocomplete for Specialist
    @RequestMapping(value = "ajaxCallForSpecialist.htm", method = RequestMethod.GET)
    public @ResponseBody
    String doAjaxAppSpecialistPopulate(HttpServletRequest request) {
        System.out.println("inside doAjaxSpecialistPopulate");
        String str = request.getParameter("term");
        System.out.println("term :" + str);
        String json;
        List<Specialist> specialists = this.specialistService.SpecialistListForAutoComplete(str);
        //System.out.println("list" + appSpecialists.size());
        Gson gson = new Gson();
        List list = new ArrayList();
        for (Specialist s : specialists) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", s.getSpecialistId());
            map.put("label", s.getName());
            map.put("value", s.getName());
            list.add(map);
        }
        Type typeList = new TypeToken<List>() {
        }.getType();
        json = gson.toJson(list, typeList);
        System.out.println("json :" + json);
        return json;
    }

    //step one
    @RequestMapping(value = "sms/updateCustomerForSms", method = RequestMethod.GET)
    public String showSmsGetPage(@RequestParam(value = "customerId") int customerId,
            ModelMap modelMap) {
        Customer customer = this.customerService.getCustomerDetails(customerId);
        modelMap.addAttribute("customer", customer);
        return "sms/updateCustomerForSms";
    }

    //step two
    @RequestMapping(value = {"sms/updateCustomerForSms"}, method = RequestMethod.POST, params = "_stepTwo")
    public String sendSmsStepTwoPage(@RequestParam(value = "customerId") int customerId,
            @RequestParam(value = "smsSituatonId", required = true) int smsSituatonId,
            ModelMap modelMap) {
        System.out.println("in sendSmsStepTwoPage");
        System.out.println("smsSituatonId :" + smsSituatonId);
        Customer customer = this.customerService.getCustomerDetails(customerId);
        //test remaining
        //SmsType smsType = this.smsService.SmsTypeName(smsSituatonId);
        SmsTemplate smsTemplate = this.smsService.SmsTemplateName(smsSituatonId);
//        Customer customerDetail = this.customerService.getCustomerListOnEmployeeId(customerId);
//        modelMap.addAttribute("customerDetail", customerDetail);
        modelMap.addAttribute("smsTemplate", smsTemplate);
        String smsTemplateName = smsTemplate.getSmsTemplateDesc();
        modelMap.addAttribute("smsTemplateName", smsTemplateName);
        modelMap.addAttribute("customer", customer);
        switch (smsSituatonId) {
            case 1:
                //System.out.println("inside case 1");
                return "sms/smsType1";
            case 2:
                //System.out.println("inside case 2");
                return "sms/smsType2";
            case 3:
                //System.out.println("inside case 3");
                return "sms/smsType3";
            case 4:
                //System.out.println("inside case 4");
                return "sms/smsType4";
            case 5:
                Customer customerDetail = this.customerService.getCustomerListOnEmployeeId(customerId);
                modelMap.addAttribute("customerDetail", customerDetail);
                //System.out.println("inside case 5");
                List<Map<String, Object>> illnessList = this.customerService.getIllnessListByCustomerId(customerId);
                //System.out.println("after illness list");
                List<Locum> locumList = this.locumService.getLocumList();
                //System.out.println("after locum list");
                List<Ambulance> ambulanceList = this.ambulanceService.getAmbulanceList();
                //System.out.println("after ambulance list");
//                if (customer.getRelation().getRelationId() != RELATION_SELF) {
//                    System.out.println("inside if");
//                    List<Customer> customerList = this.customerService.getCustomerListOnEmployeeId(empId);
//                    for (Customer c : customerList) {
//                        if (c.getRelation().getRelationId() == RELATION_SELF) {
//                            System.out.println("c.getCustomerName();"+c.getCustomerName());
//                            
//                            modelMap.addAttribute("actualEmployee", c);
//                        }
//
//                    }
//                    modelMap.addAttribute("customerList", customerList);
//                }

                modelMap.addAttribute("ambulanceList", ambulanceList);
                modelMap.addAttribute("locumList", locumList);
                modelMap.addAttribute("illnessList", illnessList);
                //System.out.println("illnessList" + illnessList);
                return "sms/smsType5";
            case 6:
                //System.out.println("inside case 6");
                return "sms/smsType6";
            case 7:
                //System.out.println("inside case 7");
                return "sms/smsType7";

            case 8:
                //System.out.println("inside case 8");
                return "sms/smsType8";
            case 9:
                //System.out.println("inside case 9");
                return "sms/smsType9";
            case 10://by santosh
                //System.out.println("inside case 10");
                return "sms/smsTypeBlank";
        }
        return null;
    }

    //step three
    @RequestMapping(value = "sms/updateCustomerForSms", method = RequestMethod.POST, params = "_finish")
    public String sendSmsFinalStepPage(@RequestParam(value = "customerId") int customerId, HttpServletRequest request, ModelMap modelMap) throws ServletRequestBindingException {

        String msgBody1 = ServletRequestUtils.getStringParameter(request, "smsType1", "");
        String msgBody2 = ServletRequestUtils.getStringParameter(request, "smsType2", "");
        String msgBody3 = ServletRequestUtils.getStringParameter(request, "smsType3", "");
        String msgBody4 = ServletRequestUtils.getStringParameter(request, "smsType4", "");
        String msgBody5 = ServletRequestUtils.getStringParameter(request, "smsType5", "");
        String msgBody6 = ServletRequestUtils.getStringParameter(request, "smsType6", "");
        String msgBody7 = ServletRequestUtils.getStringParameter(request, "smsType7", "");
        String msgBody8 = ServletRequestUtils.getStringParameter(request, "smsType8", "");
        String msgBody9 = ServletRequestUtils.getStringParameter(request, "smsType9", "");
        String msgBody10 = ServletRequestUtils.getStringParameter(request, "smsType10", "");
        String msgBody11 = ServletRequestUtils.getStringParameter(request, "smsType11", "");
        String msgBody12 = ServletRequestUtils.getStringParameter(request, "smsType12", "");
        String msgBody13 = ServletRequestUtils.getStringParameter(request, "smsType13", "");
        String msgBody14 = ServletRequestUtils.getStringParameter(request, "smsType14", "");
        //by Santosh
        String msgBodyBlank = ServletRequestUtils.getStringParameter(request, "smsTypeBlank", "");
        String phone = ServletRequestUtils.getStringParameter(request, "phone", "0");


        String locumContactNo = null;
        String hospitalContactNo = null;
        String ambulanceContactNo = null;
        Boolean flag = false;

        final String shobnaKavita = "9167998199,9930829990";
        //final String shobnaKavita = "9870342575,9004585565,9004485016";
        final String iciciManagement = "";
        final String healthSpringManagement = "8097284995,9930507999,9820186887,9819021098";
        //final String healthSpringManagement = "9870342575,9004585565,9004485016";

        // For gettting phone number of Locum 
        if (!"".equals(msgBody5) || !"".equals(msgBody10)) {
            String locumInfo = ServletRequestUtils.getStringParameter(request, "locumId");
            //System.out.println("locumInfo :" + locumInfo);
            String locumParameters[] = locumInfo.split("~");
            //System.out.println("locumParameters[1]:" + locumParameters[1]);
            locumContactNo = locumParameters[1];
            locumContactNo = locumContactNo.trim();
            //System.out.println("locumContactNo:" + locumContactNo);
        }

        // For gettting phone number of Hospital
        if (!"".equals(msgBody7)) {
            String hospitalInfo = ServletRequestUtils.getStringParameter(request, "hospitalId");
            //System.out.println("hospitalInfo:" + hospitalInfo);
            String hospitalParameters[] = hospitalInfo.split("~");
            //System.out.println("HospitalParameters[1]:" + hospitalParameters[1]);
            hospitalContactNo = hospitalParameters[1];
            hospitalContactNo = hospitalContactNo.trim();
            //System.out.println("hospitalContactNo:" + hospitalContactNo);
        }

        // For gettting phone number of Ambulance
        //if (!"".equals(msgBody6) && !"".equals(msgBody10)) {
        if (!"".equals(msgBody8)) {
            String ambulanceInfo = ServletRequestUtils.getStringParameter(request, "ambulanceId");
            //System.out.println("AmbulanceInfo:" + ambulanceInfo);
            String ambulanceParameters[] = ambulanceInfo.split("~");
            //System.out.println("ambulanceParameters[1]:" + ambulanceParameters[1]);
            ambulanceContactNo = ambulanceParameters[1];
            ambulanceContactNo = ambulanceContactNo.trim();
            //System.out.println("ambulanceContactNo :" + ambulanceContactNo);
        }

        Customer customer = this.customerService.getCustomerDetails(customerId);

        //For getting phone number of Customer
        String patientContactNo = customer.getPhone1().trim();
        List<SmsSendData> smsList = new LinkedList<SmsSendData>();

        if (!msgBody1.isEmpty()) {
            // smsMsgType 1
            //System.out.println("inside if msgBody1 is not empty");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(1);
            sms.setSmsTemplateId(1);
            sms.setSmsBody(msgBody1);
            sms.setSmsPhoneNos(patientContactNo); // send only to Customer
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        } else if (!msgBody2.isEmpty()) {
            // smsMsgType 2
            //System.out.println("inside if msgBody2!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(2);
            sms.setSmsTemplateId(2);
            sms.setSmsBody(msgBody2);
            sms.setSmsPhoneNos(patientContactNo); // send only to Customer
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        } else if (!msgBody3.isEmpty()) {
            // smsMsgType 3
            //System.out.println("inside if msgBody3!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(3);
            sms.setSmsTemplateId(3);
            sms.setSmsBody(msgBody3);
            sms.setSmsPhoneNos(patientContactNo); // send only to Customer
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        } else if (!msgBody4.isEmpty()) {
            // smsMsgType 4
            //System.out.println("inside if msgBody4!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(4);
            sms.setSmsTemplateId(4);
            sms.setSmsBody(msgBody4);
            sms.setSmsPhoneNos(patientContactNo); // send only to Customer
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        } else if (!msgBody11.isEmpty()) {
            // smsMsgType 11
            //System.out.println("inside if msgBody11!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(11);
            sms.setSmsTemplateId(11);
            sms.setSmsBody(msgBody11);
            sms.setSmsPhoneNos(patientContactNo); // send only to Customer
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        } else if (!msgBody12.isEmpty()) {
            // to Customer 
            //System.out.println("inside if msgBody12!=");
            //String phoneNumbers12="9167998199,9930829990";
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(12);
            sms.setSmsTemplateId(12);
            sms.setSmsBody(msgBody12);
            //sms.setSmsPhoneNos(shobnaKavita); // send to Shobhna and Kavita this is change on 29 jan 2013 and assign this body to another type
            sms.setSmsPhoneNos(patientContactNo);// send to Customer
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        } else if (!msgBody13.isEmpty()) {
            // to Customer 
            //System.out.println("inside if msgBody12!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(12);
            sms.setSmsTemplateId(13);
            sms.setSmsBody(msgBody13);
            sms.setSmsPhoneNos(patientContactNo);// send to Customer
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        } else if (!msgBody14.isEmpty()) {
            // to Customer 
            //System.out.println("inside if msgBody14!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(12);
            sms.setSmsTemplateId(14);
            sms.setSmsBody(msgBody14);
            sms.setSmsPhoneNos(patientContactNo);// send to Customer
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        }



        // following sms to be send in case of  Emergency 

        if (!msgBody5.isEmpty()) {
            // smsMsgType 5
            //to Locum
            //System.out.println("inside if msgBody5!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(5);
            sms.setSmsTemplateId(5);
            sms.setSmsBody(msgBody5);
            sms.setSmsPhoneNos(locumContactNo); // send only to Locum
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        }
        if (!msgBody6.isEmpty()) {
            // smsMsgType 6
            //to Customer
            //System.out.println("inside if msgBody6!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(6);
            sms.setSmsTemplateId(6);
            sms.setSmsBody(msgBody6);
            sms.setSmsPhoneNos(patientContactNo); // send only to customer
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        }
        if (!msgBody7.isEmpty()) {
            // smsMsgType 7
            //to Hospital
            //System.out.println("inside if msgBody7!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(7);
            sms.setSmsTemplateId(7);
            sms.setSmsBody(msgBody7);
            sms.setSmsPhoneNos(hospitalContactNo); // send only to Hospital
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        }

        if (!msgBody8.isEmpty()) {
            // smsMsgType 8
            //to Ambulance
            //System.out.println("inside if msgBody8!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(8);
            sms.setSmsTemplateId(8);
            sms.setSmsBody(msgBody8);
            sms.setSmsPhoneNos(ambulanceContactNo); // send only to Ambulance
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        }

        if (!msgBody9.isEmpty()) {
            // smsMsgType 9
            //to ICICI Management,Shobana & Kavita
            //System.out.println("inside if msgBody9!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(9);
            sms.setSmsTemplateId(9);
            sms.setSmsBody(msgBody9);
            sms.setSmsPhoneNos(shobnaKavita + iciciManagement); // send to ICICI Management + Shobna + Kavita
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        }

        if (!msgBody10.isEmpty()) {
            // smsMsgType 10
            //to Healthspring Management
            //System.out.println("inside if msgBody10!=");
            SmsSendData sms = new SmsSendData();
            //sms.setSmsTypeId(10);
            sms.setSmsTemplateId(10);
            sms.setSmsBody(msgBody10);
            sms.setSmsPhoneNos(healthSpringManagement); // send to Health Spring Management
            if (!isValidPhoneNo(sms.getSmsPhoneNos())) {
                sms.setSmsStatus("Permanent failure");
            }
            smsList.add(sms);
        }
        if (!msgBodyBlank.isEmpty()) {
            //By Santosh
            SmsSendData sendData = new SmsSendData();
            sendData.setSmsTemplateId(15);
            sendData.setSmsBody(msgBodyBlank);
            sendData.setSmsPhoneNos(phone.trim());
            smsList.add(sendData);
        }
        for (SmsSendData smsData : smsList) {
//            System.out.println("inside loop");
            if (smsData.getSmsStatus() == null) {
                smsData.setSmsStatus(this.smsService.sendSms(smsData, customerId));
            } else {
                return "redirect:../customer/editCustomer.htm?customerId=" + customerId + "&error=msg.notValidPhoneNumber";
            }
        }
        modelMap.addAttribute("smsSendList", smsList);
        return "sms/smsStatus";
    }

    @RequestMapping(value = "sms/updateCustomerForSms", method = RequestMethod.POST, params = "_cancel")
    public String CancelSendSMS(@ModelAttribute("customer") Customer customer) {
        customer = null;
        return "redirect:../customer/followupList.htm?msg=Action cancelled";
    }

    @RequestMapping(value = "sms/smsStatus", method = RequestMethod.GET)
    public String showSmsStatusPage(@RequestParam(value = "phoneNo") String phoneNo,
            @RequestParam(value = "msgBody") String msgBody, ModelMap modelMap) {
        modelMap.addAttribute("phoneNo", phoneNo);
        modelMap.addAttribute("msgBody", msgBody);
        return "sms/smsStatus";
    }

    //@shedular comes here
    @Scheduled(fixedRate = 60000)
    public void reSendSmsSchdular() {
        //System.out.println("inside resend");
        List<SmsDetails> smsFailedList = this.smsService.getFailedSmsList();
        for (SmsDetails sms : smsFailedList) {
            this.smsService.reSendSms(sms, sms.getCustomerId());
        }
    }

    private boolean isValidPhoneNo(String phoneNo) {
        if (phoneNo != null) {
            if (phoneNo.length() < 10) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }
}